package ym.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ym.mapper.AdminMapper;
import ym.pojo.Admin;
import ym.pojo.AdminRole;
import ym.pojo.Permission;

import java.util.List;

@DubboService
@Transactional
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AdminRoleService adminRoleService;

    @Override
    public void add(Admin admin) {
        adminMapper.insert(admin);
        //初始化用户角色【不然添加后什么角色都没有，会报错】
        AdminRole adminRole = new AdminRole();
        adminRole.setAdminId(admin.getAdminId());
        adminRole.setRoleId(2);
        adminRoleService.add(adminRole);
    }

    @Override
    public void update(Admin admin) {
        adminMapper.updateById(admin);
    }

    @Override
    public void delete(Integer id) {
        // 删除用户
        adminMapper.deleteById(id);
        // 删除用户的所有角色
        adminRoleService.deleteByAdminId(id);
    }

    @Override
    public Admin findById(Integer id) {
        return adminMapper.findById(id);
    }

    @Override
    public Page<Admin> search(int page, int size) {
        return adminMapper.selectPage(new Page<>(page, size), null);
    }

    @Override
    public void updateStatus(Integer id) {
        Admin admin = adminMapper.selectById(id);
        if (admin.getAdminStatus().equals("1")) {
            admin.setAdminStatus("0");
        } else {
            admin.setAdminStatus("1");
        }
        adminMapper.updateById(admin);
    }
    @Override
    public void updateRole(Integer adminId, Integer[] roleIds) {
        // 删除用户的所有角色
        adminRoleService.deleteByAdminId(adminId);
        // 重新添加管理员角色
        for (Integer roleId : roleIds) {
            AdminRole adminRole = new AdminRole();
            adminRole.setAdminId(adminId);
            adminRole.setRoleId(roleId);
            adminRoleService.add(adminRole);
        }
    }

    @Override
    public Admin findByAdminName(String adminName) {
        QueryWrapper<Admin> wrapper = new QueryWrapper();
        wrapper.eq("adminName", adminName);
        Admin admin = adminMapper.selectOne(wrapper);
        return admin;
    }

    @Override
    public List<Permission> findAllPermissionByAdminName(String adminName) {
        return adminMapper.findAllPermission(adminName);
    }
}
